package com.levenx.service.support;

import com.levenx.constant.FileConstant;
import com.levenx.service.FileService;
import com.levenx.utils.Assert;
import com.levenx.vo.Result;
import com.levenx.vo.support.FileResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;

@Service
public class DefaultFileServiceImpl implements FileService {


    @Autowired
    private FileConstant fileConstant;

    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public Result<?> upload(MultipartFile file) {
        //判断数据是否为空
        Assert.isNull(file,"404");
        //数据不为空创建文件夹
        File file1 = new File(fileConstant.getPath());
        if (!file1.exists()) {
            //文件不存在,创建文件夹
            file1.mkdirs();
        }
        //校验文件是否符合我们规定的几种数据格式
        //获取上传文件的名字
        String mulName = file.getOriginalFilename();
        //获取文件后缀名
        String name = mulName.substring(mulName.lastIndexOf(".") + 1);
        //判断后缀名是否符合规范
        //定义新的图片文件名
        String picName = UUID.randomUUID().toString().replaceAll("-", "")+ "." + name;
        //创建一个新的文件对象
        File filePic = new File(file1.getPath(), picName);
        //把图片保存到服务器上
        try {
            file.transferTo(filePic);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new FileResult(picName,mulName);
    }

    @Override
    public ResponseEntity<?> getFile(String fileName) {
        return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(fileConstant.getPath(), fileName).toString()));
    }

    @Override
    public Result<?> list() {
        File file = new File(fileConstant.getPath());
        File[] listFiles = file.listFiles();
        List<Map<String,String>> result = new ArrayList<>();
        for (File listFile : listFiles) {
          result.add(new HashMap<String,String>(){{
              put("name",listFile.getName());
          }});
        }
        return Result.newResult(result);
    }

    @Override
    public Result<?> del(String name) {
        File file = new File(fileConstant.getPath(),name);
        file.delete();
        return Result.newResult();
    }
}
